package com.yyh.common;

import java.io.*;

/**
 * @author xuan
 * @date 2021/12/14
 */
public class IOCommon
{
    private static final String CHARACTER_ENCODING = "UTF-8";

    /** InputStream ==> String对象 */
    public static String readAsString(InputStream stream) {
        try {
            return new String(readAsBytes(stream), CHARACTER_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    /** InputStream ==> byte[] */
    public static byte[] readAsBytes(InputStream stream) {
        try {
            if (null == stream) {
                return new byte[0];
            } else {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                byte[] buff = new byte[1024];

                while (true) {
                    int len = stream.read(buff);
                    if (len == -1) {
                        // 此方法应该会关闭流吧
                        byte[] ret = os.toByteArray();
                        return ret;
                    }
                    os.write(buff, 0, len);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e.getCause());
        } finally {
            if (null != stream) {
                try {
                    stream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e.getMessage(), e.getCause());
                }
            }
        }
    }

    public static void writeToString(OutputStream stream, String str) {
        try {
            writeToBytes(stream, str.getBytes(CHARACTER_ENCODING));
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    public static void writeToBytes(OutputStream stream, byte[] bytes) throws IOException {
        try{
            // 覆盖
            stream.write(bytes);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e.getCause());
        } finally {
            if (null != stream) {
                try {
                    stream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e.getMessage(), e.getCause());
                }
            }
        }
    }
}
